package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Server5 {
    /**ServerSocket
     * 1.向服务器申请服务端口，客户端通过端口与服务器连接
     *端口范围在0~65535之间
     * 2.监听服务端口，一旦一个客户端连接了就会立即创建一个Socket与其交流
     */
    private ServerSocket serverSocket;
    private List<PrintWriter> allOut=new ArrayList<>();
    public Server5() {
        try {
            /*
            如果端口被占用了，则会发生异常：
            解决办法：更换端口号
            关闭占用该端口的进程
             */
            System.out.println("正在启动服务器");
            serverSocket =new ServerSocket(9999);
            System.out.println("服务器启动成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start()  {
        /*
        accept()会返回一个Socket
        用于接收客户端的连接，并返回一个Socket实例对象与客户端交互
        该方法是一个阻塞方法，调用后程序会暂停，直到有客户端连接
         */
        try {
            while(true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println("客户端连接成功");
                Runnable r1=new ClientHandler(socket);
                Thread t1=new Thread(r1);
                t1.start();



            }

        } catch (IOException e) {
            e.printStackTrace();
        }




    }
    public static void main(String[] args) {
        Server5 server=new Server5();
        server.start();




    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;

        public ClientHandler(Socket socket){
            this.socket=socket;
            host=socket.getInetAddress().getHostAddress();
        }
        //创建一个有参构造来接收外部类的参数，先要用一个全局变量来接收

        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                OutputStream os=socket.getOutputStream();
                OutputStreamWriter osw=new OutputStreamWriter(os,StandardCharsets.UTF_8);
                BufferedWriter bw=new BufferedWriter(osw);
                PrintWriter pw=new PrintWriter(bw,true);

                //将对应客户端的输出流存入到共享集合allOut中，便于其他线程可以访问到
                allOut.add(pw);

                String message;
                //当我们读取到客户端发送的字符串时，当客户端调用socket.close()正常断开
                //readLine()才会返回null
                while ((message = br.readLine()) != null) {
                    System.out.println(host+"：" + message);
                    for(PrintWriter o:allOut){
                        o.println(host+":"+message);
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
